/*
 * @Description:
 * @Version: 2.0
 * @Autor: huangfu
 * @Date: 2020-09-14 16:21:22
 * @LastEditors: 大司马
 * @LastEditTime: 2020-12-23 18:39:22
 */
import Vue from 'vue'
import Router, { RouteConfig } from 'vue-router'
import routes from './routers'
import store from '@/store'
import Cookies from 'js-cookie'
import ViewUI from 'view-design';
import { canTurnTo, setTitle } from '@/libs/util'
import { platformLogin, userInfo2, userInfo } from '@/libs/login'
import {
    goHasRoute,
    refreshLogOut
} from '@/libs/tools'
import config from '@/config/index'
import Main from '@/components/main'
import { getNextRoute } from '../libs/util'

const LOGIN_PAGE_NAME = 'login'
Vue.use(Router)
const router = new Router({
    routes,
    mode: 'hash'
})

const turnTo = (to, access, next) => {
    if (canTurnTo(to.name, access, routes)) {
        refreshLogOut((isBoolean) => {
            if (isBoolean !== false) {
                next()
            }
        })
    } else {
        goHasRoute(to, access, routes, next, )
    }
}

if (window.__POWERED_BY_QIANKUN__) {
    router.beforeEach((to, from, next) => {
        if (!to.path.includes('/microApp/dev')) {
            next({
                path: '/microApp/dev' + to.path
            })
        } else {
            next()
        }
    })
} else {
    router.beforeEach(async(to, from, next) => {
        setTitle(to, router.app)
        const url = location.href
        const token = Cookies.get('token')
        if ((url.indexOf('?') > -1 && (url.indexOf('code=') > -1) || url.indexOf('token=') > -1) && !token) {
            ViewUI.LoadingBar.start()
            platformLogin(next, to.path)
        } else {
            if (!token) return platformLogin(next)
            if (store.state.user.access.length) {
                turnTo(to, store.state.user.access, next)
            } else {
                // store.dispatch('getUserInfo').then(user => {
                //     turnTo(to, [], next)
                // }).catch(() => {
                //     store.state.user.commit('setToken', '')
                //     next({
                //         name: 'login'
                //     })
                // })
                await userInfo()
                turnTo(to, store.state.user.access, next)
            }
        }
    })
}

const originalPush = Router.prototype.push
Router.prototype.push = function push(location, onResolve, onReject) {
    if (onResolve || onReject) return originalPush.call(this, location, onResolve, onReject)
    return originalPush.call(this, location).catch(err => err)
}

router.afterEach(to => {
    ViewUI.LoadingBar.finish()
    window.scrollTo(0, 0)
})

export default router